<style scoped>
  .rj-topbar {
    height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative
  }
  .list {
    background: #eee;
  }
  .weui-form-preview {
    background-color: #fff;
    margin: 5px;
    border-radius: 5px;
  }
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui_navbar_item {
    font-size: 14px;
  }
  .weui_navbar_item.weui_bar_item_on {
    color: #3cc51f;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .list {
    overflow: auto;
  }
  .rj-cell {
    display: inline-block;
    font-size: 0;
    padding: 5px 15px;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell.minpad{
    padding-right: 10px !important;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
  }
  .rj-cell span {
    padding-left: 5px;
    font-size: 14px;
    color: #333;
  }
  .rj-cell.note{
    width: 100%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .rj-wrap {
    background: #eee;
    overflow:auto;overflow-x: hidden
  }
  .rj-cont {
    background: #fff;
  }
  .weui-panel {
    background: #eee;
  }
  .rj-cont-tit {
    margin: 0;
    border-radius: 0;
  }
  .weui-panel {
    margin-top: 0;
    text-align: left;
  }
  .demos-content-padded {
    padding: 15px;
  }
  .attachimg {
    /*width: 100%;*/
  }
  .tipp {
    position: absolute;top: 0px;background: rgba(255,0,0,0.5);color:#fff;display: inline-block;width: 85px;text-align: center;
  }
  .rj-cell-child-tit {
    background: #f9f9f9;
    font-size: 14px;
    padding: 5px 15px;
    border-bottom: 1px solid #eee;
  }
  .divideline {
    background: #eee;
    height: 4px;
  }
  .banlance {
    background: #fff;
    padding: 10px 15px;
  }
  .banlance h2 {
    padding: 10px 0;
    font-size: 14px;
    font-weight: 600;
  }
  .cashbox p {
    border: 1px solid #ccc;
    display: inline-block;
    margin: 3px;
    padding: 5px 10px;
  }
  .cashbox p input {
    border: 0;
  }
  .cashbox p.active {
    border-color: #1aad19;
  }
  .recharge {height: 100%; background: #eee;}

  .weui-form-preview {
    background-color: #fff;
    margin: 5px;
    border-radius: 5px;
  }
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell {
    display: inline-block;
    font-size: 0;
    padding: 5px 15px;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
  }
  .rj-cell span {
    padding-left: 5px;
    font-size: 14px;
    color: #333;
  }
  .rj-cell span i {
    color: red;
    font-size: 30px;
    font-style: normal;
  }
  .paylayer .rj-cell {
    padding: 5px;
  }
  .weui-panel {
    background: #eee;
  }
  .rj-cont-tit {
    margin: 0;
    border-radius: 0;
    text-align: left;
  }
  .weui-panel {
    margin-top: 0;
  }
  .all-btn i {
    font-size: 16px;
    position: absolute;
    left: -7px;
    top: 8px;
  }
  .weui-cell:before {
    border-top: 0;
  }
  .weui-select {
    font-size: 14px;
    color: #333;
  }
  .weui-cell__hd {
    font-size: 14px;
    color: #333;
    padding: 5px 15px;
  }
  .weui-textarea {
    font-size: 14px;
  }


  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_files {
    list-style: none;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .outstore >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }
  .outstore >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
  .weui-cell.fir {
    border-top: 0;
  }
  .help {
    text-align: right;
    padding: 5px;
    font-size: 12px;
    color: #bbb;
  }
  .weui_uploader_input_wrp.inrow {
    width: 30px;
    height: 30px;
    margin: 0;
  }
  .weui_uploader_input_wrp:before {
    height: 19.5px;
  }
  .weui_uploader_input_wrp:after {
    width: 19.5px;
  }
  .weui-uploader_file.inrow {
    margin: 0;
    width: 40px;
    display: inline-block;
  }
</style>
<template>
  <div class="recharge">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      {{title}}
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-panel weui-panel_access">
      <div class="weui-panel__bd">
        <div class="weui-form-preview billitem rj-cont-tit">
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">部门：</label></div>
            <div class="weui-cell__bd" style="display: inline-block;z-index: 0;">
              <input type="hidden" name="entity.departname" :value="depart.name" />
              <input type="hidden" name="entity.departid" :value="depart.guid" />
              <select class="weui-select" v-model="depart">
                <option value="">请选择部门</option>
                <option selected=""  v-for="(item, index) in departments" :key="item.guid" :value="item">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="rj-cell max">
            <label>客户：</label>
            <span>{{customer.name}}</span>
          </div>
          <div class="rj-cell max">
            <label>地址：</label>
            <span>{{customer.province + customer.city + customer.district}} {{customer.address}}</span>
          </div>
          <div class="rj-cell max">
            <label>余额：</label>
            <span style="color: red;">{{customer.prebalance}}</span>
            <label>货币预收款余额：</label>
            <span style="color: red;">{{customer.currPrebalance}}</span>
          </div>
          <div class="rj-cell max">
            <label>非货币预收款余额：</label>
            <span style="color: red;">{{customer.nocurrPrebalance}}</span>
          </div>
        </div>
        <div class="divideline"></div>
        <div class="banlance">
          <h2>充值金额</h2>
          <div class="cashbox">
            <p :class="{active: amount == 10000}" @click="setAmount(10000)">10000元</p>
            <p :class="{active: amount == 50000}" @click="setAmount(50000)">50000元</p>
            <p :class="{active: amount == 100000}" @click="setAmount(100000)">100000元</p>
            <p><input type="number" name="amount" placeholder="自定义金额" v-model="amount"></p>
          </div>
        </div>
        <div class="weui-cell" style="background: #fff;">
          <div class="weui-cell__bd">
            <textarea class="weui-textarea" name="remark" v-model="opinion" placeholder="请输入备注内容" rows="3"></textarea>
          </div>
        </div>
        <div class="weui-cell">
          <div class="weui-cell__hd" style="padding: 0;"><label class="weui-label">单据上传</label></div>
          <div class="weui-cell__ft">
            <div class="weui_uploader_bd"><ul class="weui_uploader_files"></ul><div class="weui_uploader_input_wrp inrow"><input type="button" id="selectImage"  class="weui_uploader_input" ></div></div>
          </div>
          <ul class="weui_uploader_files" id="image" style="font-size: 0; margin-right: 5px;">
            <li class="weui-uploader_file inrow" v-for="(img, index) in images.serverId" :id="img"  @click=del(img,2) ><img :src="images.srcStr[index]" width="30"/></li>
          </ul>
        </div>

      </div>
    </div>
    <div class="catbtn">
      <div class="demos-content-padded">
        <a href="javascript:;" class="weui-btn weui-btn_primary subbtn" @click="send">确定</a>
      </div>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';

  export default {
    name: 'Recharge',
    data () {
      return {
        id: '',
        type: '',
        customer: '',
        amount: '',
        opinion: '',
        departments: [],
        depart: "",
        images: {
          serverId: [],
          srcStr: [],
        }
      }
    },
    created() {

    },
    mounted () {
      this.id = this.$route.query.id;
      this.type = this.$route.query.type;
      this.getCustomer(this.id);
      this.getDepartment();
    },
    computed: {
      title: function () {
        let txt = '';
        switch (this.type) {
          case 1:
            txt = '预收款货币充值';
            break;
          case 2:
            txt = '预收款非货币充值';
            break;
        }
        return txt;
      }
    },
    methods: {
      wxConfig: function(wxParams) {
        wx.config({
          debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: wxParams.appid,    // 必填，公众号的唯一标识
          timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
          nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
          signature: wxParams.signature,// 必填，签名
          jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
        });
      },
      wxUoloadImage: function(that) {
        let cthis = this;
        //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images.srcStr.push(n);
                        })
                      }

                      cthis.images.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
        //});

      },
      del: function (id){
        let cthis = this;
        $.actions({
          actions: [{
            text: "删除",
            onClick: function() {
              $.confirm("确定删除?", function() {
                //点击确认后的回调函数
                //删掉id
                var ids = cthis.images.serverId;
                var a =  ids.indexOf(id);
                cthis.$nextTick(function () {
                  cthis.images.serverId.splice(a,1);
                  cthis.images.srcStr.splice(a,1);
                })
                //$("#"+id).hide();
              }, function() {
                //点击取消后的回调函数
              });
            }
          }
          ]
        });
      },
      checkCore:function() {
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
        if (isIOS) {
          return 'ios';
        } else  {
          return 'android';
        }
      },
      getDepartment: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDepartment.action',
          params: {sPermission: 2}
        }).then(response => {
          if (response.data.status == "true") {
            //that.departments = response.data.result.map(that.filterDepartment);
            that.departments = response.data.result;
            that.depart = response.data.result.length > 0 ? response.data.result[0] : '';
          } else {
            this.toastText('获取部门数据失败');
          }
        });
      },
      getCustomer: function (id) {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Customer!detail.action',
          params: {customerid: id, url: location.href.split("#")[0]}
        }).then(response => {
          if (response.data.msg == 'success') {
            let res = response.data;
            this.customer = res.customer;

            let wxParams = response.data.params;
            //配置微信公众号参数
            this.wxConfig(response.data.params);
            //上传
            this.wxUoloadImage(that);
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastError('系统错误');
        }
        });
      },
      setAmount: function (amount) {
        this.$nextTick(() => {
          this.amount = amount;
        })
      },
      send: function () {
        let that = this;

        if (this.depart == '') {
          this.toastText('请选择部门！');
          return false;
        } else if (this.amount == '') {
          this.toastText('请输入充值金额！');
          return false;
        } else if (this.images.serverId.length == 0) {
          this.toastText('单据不能为空！');
          return false;
        }

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData =  {
          'recharge.type': this.type,
          'recharge.guid': this.id,
          'recharge.departid': this.depart.guid,
          'recharge.departname': this.depart.name,
          'recharge.customerid': this.customer.guid,
          'recharge.customer': this.customer.name,
          'recharge.amount': this.amount,
          'recharge.remark': this.opinion
        }
        postData.imgids = this.images.serverId.join(',');

          this.axios({
          method: 'post',
          url: '/sales/Recharge!save.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if(response.data.msg == "success"){
            this.toastText('操作成功!');
            this.$router.push({name: 'ViewCustomer', query: {id: this.id}});
          }else if (response.data.msg == 'canotRecharge'){
            if (this.type == 1) {
              this.toastText('货币预收款余额不能为负数!');
            } else if (this.type == 2) {
              this.toastText('非货币预收款余额不能为负数!');
            }
          }else if (response.data.msg == 'canotopt'){
            this.toastText('不允许的操作!');
          }else {
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      }
    }
  }
</script>
